package com.sc.sc250601.cook.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sc.sc250601.cook.handler.SocketIOHandler;
import com.sc.sc250601.cook.mapper.UserFollowMapper;
import com.sc.sc250601.cook.pojo.Notification;
import com.sc.sc250601.cook.pojo.UserFollow;
import com.sc.sc250601.cook.service.NotificationService;
import com.sc.sc250601.cook.service.UserFollowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserFollowServiceImpl implements UserFollowService {
    @Autowired
    UserFollowMapper userFollowMapper;
    @Autowired
    NotificationService notificationService;

    public List<Long> selectAllFollowedId(Long id) {
        List<UserFollow> luf=userFollowMapper.selectAllFollowedId(id);
        List<Long> ids=new ArrayList<>();
        for(UserFollow uf:luf){
            ids.add(uf.getFollowedId());
        }
        return ids;
    }


    public int add(UserFollow uf) {
        return userFollowMapper.insert(uf);
    }


    public int del(UserFollow uf) {
        return userFollowMapper.del(uf);
    }

    /**
     * 当用户发布新内容时，推送通知给粉丝
     */
    public void pushNewContentToFans(Long authorId, String authorName, String contentTitle, Long contentId) {
        // 1. 获取该作者的所有粉丝ID
        List<Long> fansIds = userFollowMapper.selectFansByAuthorId(authorId);  // 需要在Mapper中实现

        if (fansIds == null || fansIds.isEmpty()) {
            System.out.println("作者[" + authorId + "]没有粉丝，无需推送");
            return;
        }

        // 2. 构建通知消息
        Map<String, Object> message = new HashMap<>();
        message.put("type", "new_content");  // 消息类型
        message.put("authorId", authorId);   // 作者ID
        message.put("authorName", authorName);  // 作者昵称
        message.put("title", contentTitle);  // 帖子标题
        message.put("contentId", contentId);  // 帖子ID（用于跳转）
        message.put("time", System.currentTimeMillis());  // 时间戳

        // 3. 调用SocketIO处理器推送消息给所有粉丝
        SocketIOHandler sh=new SocketIOHandler();
        sh.pushToUsers(fansIds, message);

        //处理离线的问题--添加通知表中的信息
        List<Notification> notifications=new ArrayList<>();
        for(Long uid:fansIds){
            Notification n=new Notification();
            n.setUserId(uid);
            n.setAuthorId(authorId);
            n.setContentId(contentId);
            n.setTitle(contentTitle);
            n.setAuthorName(authorName);
            n.setIsRead(false);
            notifications.add(n);
        }
        //批量新增通知
        notificationService.addNotifications(notifications);



        System.out.println("已向[" + fansIds.size() + "]个粉丝推送新内容通知");
    }

}
